package com.hospital.insurancedip.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospital.common.core.function.PushMessage;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.DateUtil;
import com.hospital.common.core.utils.SpringContextHolder;
import com.hospital.insurancedip.async.WxPayFunc;
import com.hospital.insurancedip.module.entity.*;
import com.hospital.insurancedip.module.entity.insur.InputComm;
import com.hospital.insurancedip.module.entity.insur.Minsur1101Input;
import com.hospital.insurancedip.module.entity.insur.Minsur5204Req;
import com.hospital.insurancedip.module.mapper.InsuranceLogsMapper;
import com.hospital.insurancedip.module.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Yeman
 * @Date: 2023-04-03-14:51
 * @Description:
 */
@Slf4j
public class Dip990206Up extends AbstractMessageInfo {

    private HospitalConfigService hospitalConfigMapper = SpringContextHolder.getBean(HospitalConfigService.class);
    private Minsur1101BaseinfoService minsur1101BaseinfoMapper = SpringContextHolder.getBean(Minsur1101BaseinfoService.class);
    private Minsur1101InsuinfoService minsur1101InsuinfoMapper = SpringContextHolder.getBean(Minsur1101InsuinfoService.class);
    private Minsur1101IdetinfoService minsur1101IdetinfoMapper = SpringContextHolder.getBean(Minsur1101IdetinfoService.class);
    private Minsur2301ResultService minsur2301ResultMapper = SpringContextHolder.getBean(Minsur2301ResultService.class);
    private Minsur2304SetldetailService minsur2304SetldetailMapper = SpringContextHolder.getBean(Minsur2304SetldetailService.class);
    private Minsur2304SetlinfoService minsur2304SetlinfoMapper = SpringContextHolder.getBean(Minsur2304SetlinfoService.class);
    private BaglBasyHisService baglBasyHisService = SpringContextHolder.getBean(BaglBasyHisService.class);
    private RestTemplate restTemplate = SpringContextHolder.getBean(RestTemplate.class);
    private WxPayFunc wxPayFunc = SpringContextHolder.getBean(WxPayFunc.class);
    private InpSettleMasterService inpSettleMasterService = SpringContextHolder.getBean(InpSettleMasterService.class);
    private InsuranceLogsMapper insuranceLogsMapper = SpringContextHolder.getBean(InsuranceLogsMapper.class);
    private PushMessage pushMessage = SpringContextHolder.getBean(PushMessage.class);


    @Override
    Tip getUpDetail(JSONObject requestVal) {
        Tip tip = new SuccessTip();
        //高新的需要从电子病历数据库查
        if (requestVal.getString("fixmedins_code").equals("H61030200230") || requestVal.getString("fixmedins_code").equals("H61032302183")) {
            try {
                String patient_id = requestVal.getString("patient_id");
                String visitId = requestVal.getString("visit_id");

                //之前从电子病历数据库查数据获得病案首页数据
//            Dip990206Entity bypatId = baglBasyService.getBypatIdNew(patient_id + "==" + visitId);
//            String JsonStr = JsonUtils.objectToJson(bypatId);
//            JSONObject jsonObject = JSON.parseObject(JsonStr);
//            jsonObject = setDate("ssjczrq1","yyyy-MM-dd",jsonObject);
//            jsonObject = setDate("ssjczrq2","yyyy-MM-dd",jsonObject);
//            jsonObject = setDate("rysj","yyyy-MM-dd HH:mm:ss",jsonObject);
//            jsonObject = setDate("cysj","yyyy-MM-dd HH:mm:ss",jsonObject);
//            jsonObject = setDate("zkrq","yyyy-MM-dd HH:mm:ss",jsonObject);
//            jsonObject = setDate("ssjczrq3","yyyy-MM-dd",jsonObject);
//            jsonObject = setDate("ssjczrq5","yyyy-MM-dd",jsonObject);
//            jsonObject = setDate("ssjczrq4","yyyy-MM-dd",jsonObject);
//            JSONArray jsonObject1 = new JSONArray();
//            jsonObject1.add(jsonObject);
//            JSONObject jsonObject2 = new JSONObject();
//            jsonObject2.put("list", jsonObject1);
//            requestVal.put("input", jsonObject2);
                //现在电子病历推动病案首页数据给HIE
                JSONObject input = requestVal.getJSONObject("input");
                JSONArray data = input.getJSONArray("data");
//                if (data.size()==0){
//                    data = new JSONArray();
//                    BaglBasyHis baglBasyHis = new BaglBasyHis();
//                    String string1 = JSON.toJSONString(baglBasyHis, SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteBigDecimalAsPlain,
//                            SerializerFeature.WriteDateUseDateFormat);
//                    data.add(string1);
//                    input.put("data",data);
//                    requestVal.put("input",input);
//                    String string = requestVal.toJSONString();
//                    log.info(string);
//                }
                for (Object object : data) {
                    BaglBasyHis baglBasyHis = JSON.parseObject(object.toString(), BaglBasyHis.class);
                    //dip结算清单上传
                    try {
                        if (baglBasyHis.getInhouseFlag().equals("2")) {
                            sendDip(patient_id, visitId, requestVal, baglBasyHis);
                        }
                    } catch (Exception e) {
                        log.error("\r\n患者id:【" + patient_id + "】第【" + visitId + "】次数住院的结算清单传输异常:" + e.getMessage());
                    }
                    if (ObjectUtil.isNull(patient_id)) {
                        patient_id = baglBasyHis.getPatientId();
                    }
                    if (ObjectUtil.isNull(visitId)) {
                        visitId = String.valueOf(baglBasyHis.getVisitId());
                    }
                    BaglBasyHis baglBasyHisOld = baglBasyHisService.getOne(new QueryWrapper<BaglBasyHis>().eq("PATIENT_ID", patient_id).eq("VISIT_ID", visitId));
                    boolean insert = false;
                    if (ObjectUtil.isNull(baglBasyHisOld)) {
                        baglBasyHis.setPatientId(patient_id);
                        baglBasyHis.setVisitId(Integer.valueOf(visitId));
                        insert = baglBasyHisService.save(baglBasyHis);
                    } else {
                        insert = baglBasyHisService.update(baglBasyHis, new QueryWrapper<BaglBasyHis>().eq("PATIENT_ID", patient_id).eq("VISIT_ID", visitId));
                    }
                    if (!insert) {
                        tip.setCode(303);
                        tip.setMessage("更新或写入电子病历西医病案首页数据异常！");
                        return tip;
                    }
                }
            } catch (Exception e) {
                return new ErrorTip(302, e.getMessage());
            }
        }
        tip.setData(requestVal);
        tip.setCode(200);
        return tip;
    }

    @Override
    Tip sendOther(JSONObject requestVal) {
        return null;
    }


    public void sendDip(String patientId, String visitId, JSONObject jsonObject, BaglBasyHis baglBasy) throws ParseException {
        String patientInfo = patientId + visitId;
        //封装结算清单给银海接口
        Minsur2304Setlinfo minsur2304Setlinfo = minsur2304SetlinfoMapper.getOne(new QueryWrapper<Minsur2304Setlinfo>().apply(" REFUND_FLAG is null and patient_info={0}", patientInfo));
        String substring = minsur2304Setlinfo != null ? minsur2304Setlinfo.getMedinsSetlId().substring(0, 1) : "";
        List<String> medTypeList = new ArrayList<>();
        //普通住院（21）、重大疾病住院（210101），急诊住院（210104），分级诊疗住院（210304），外伤住院（22），转外诊治住院（23），急诊转住院（24）
        medTypeList.add("21");
        medTypeList.add("210101");
        medTypeList.add("210104");
        medTypeList.add("210304");
        medTypeList.add("22");
        medTypeList.add("23");
        medTypeList.add("24");
        if (minsur2304Setlinfo != null && substring.equals("H") && medTypeList.contains(minsur2304Setlinfo.getMedType())) {
            String setlId = minsur2304Setlinfo.getSetlId();
            String mdtrtId = minsur2304Setlinfo.getMdtrtId();
            String psnNo = minsur2304Setlinfo.getPsnNo();
            List<Minsur2304Setldetail> minsur2304SetldetailList = minsur2304SetldetailMapper.list(new QueryWrapper<Minsur2304Setldetail>().eq("setl_id", setlId));
            PatientInfo inpNoByPid = minsur2301ResultMapper.getInpNoByPid(patientId);
            String zjhm = StringUtils.isBlank(baglBasy.getZjhm()) || baglBasy.getZjhm().equals("") ?
                    StringUtils.isBlank(inpNoByPid.getIdNo()) || inpNoByPid.getIdNo().equals("") ? "" : inpNoByPid.getIdNo() : baglBasy.getZjhm();

            //处理患者医保基本信息异常

            Minsur1101Baseinfo minsur1101Baseinfo = minsur1101BaseinfoMapper.getOne(new QueryWrapper<Minsur1101Baseinfo>().eq("patient_id", patientId));
            if (ObjectUtil.isNull(minsur1101Baseinfo)) {
                if (StringUtils.isBlank(zjhm) || zjhm.equals("")) {
                    throw new NullPointerException("patientId【" + inpNoByPid.getPatientId() + "】患者身份证信息从病案及基本信息中获取不到，请核查！");
                }
                Minsur1101Input minsur1101Input = new Minsur1101Input();
                minsur1101Input.setPatient_id(patientId);
                minsur1101Input.setPsn_name(baglBasy.getName());
                minsur1101Input.setMdtrt_cert_no("SFZ;" + zjhm + ";" + baglBasy.getName());
                JSONObject jsonObject1101 = new JSONObject();
                jsonObject1101.put("data", minsur1101Input);
                getInsurBase(patientId, zjhm, "1101", jsonObject1101, visitId);
                minsur1101Baseinfo = minsur1101BaseinfoMapper.getOne(new QueryWrapper<Minsur1101Baseinfo>().eq("patient_id", patientId));
                if (ObjectUtil.isNull(minsur1101Baseinfo)) {
                    throw new NullPointerException("patientId【" + inpNoByPid.getPatientId() + "】医保基本信息为空且获取异常，核查后再上传！");
                }
            }
            //费用明细表中为空的情况处理及费用不符合时，重新查医保费用
            List<IteminfoBeanHIs> minsur2301ResultList = minsur2301ResultMapper.getBysql(mdtrtId, "minsur_2301_result");
            BigDecimal reduce = minsur2301ResultList.stream().map(IteminfoBeanHIs::getAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal medfeeSumamt = minsur2304Setlinfo.getMedfeeSumamt();
            if (CollectionUtils.isEmpty(minsur2301ResultList) || reduce.compareTo(medfeeSumamt) != 0) {
                Minsur5204Req minsur5204Reqn = new Minsur5204Req();
                minsur5204Reqn.setMdtrt_id(mdtrtId);
                minsur5204Reqn.setSetl_id(setlId);
                minsur5204Reqn.setPsn_no(psnNo);
                JSONObject jsonObject5204 = new JSONObject();
                jsonObject5204.put("data", minsur5204Reqn);
                getInsurBase(patientId, zjhm, "5204", jsonObject5204, visitId);
                minsur2301ResultList = minsur2301ResultMapper.getBysql(mdtrtId, "minsur_5204_result");
                if (CollectionUtils.isEmpty(minsur2301ResultList)) {
                    throw new NullPointerException("patientId【" + inpNoByPid.getPatientId() + "】医保费用明细信息为空或金额不符或获取异常，核查后再上传！");
                }
            }

            Minsur1101Insuinfo minsur1101Insuinfo = minsur1101InsuinfoMapper.getOne(new QueryWrapper<Minsur1101Insuinfo>().eq("psn_no", psnNo));
            Minsur1101Idetinfo minsur1101Idetinfo = minsur1101IdetinfoMapper.getOne(new QueryWrapper<Minsur1101Idetinfo>().eq("psn_no", psnNo));
            Minsur410100 minsur410100 = JSON.parseObject(jsonObject.toJSONString(), Minsur410100.class);
            minsur410100.setInfno("410100");


            InpSettleMaster inpSettleMaster = inpSettleMasterService.getOne(new QueryWrapper<InpSettleMaster>().apply("patient_id = {0} and visit_id = {1}", patientId, visitId));
            if (ObjectUtil.isNull(inpSettleMaster)) {
                throw new NullPointerException("patientId【" + inpNoByPid.getPatientId() + "】患者HIS系统未结算，无法获取信息暂时无法上传！");
            }
            //input
            Minsur410100.InputBeanInsur inputBeanInsur = new Minsur410100.InputBeanInsur();

            String updateDate = DateUtil.getTime();
            String brty = DateUtil.format(minsur1101Baseinfo.getBrdy(), "yyyy-MM-dd");

            //setlinfo
            Minsur410100.InputBeanInsur.SetlinfoBean setlinfoBean = new Minsur410100.InputBeanInsur.SetlinfoBean();
            setlinfoBean.setMdtrt_id(mdtrtId);
            setlinfoBean.setSetl_id(setlId);
            setlinfoBean.setAdm_dept_code(baglBasy.getRykbdm());
            setlinfoBean.setAdm_dept_name(baglBasy.getRykb());
            String cyksdm = baglBasy.getCyksdm();
            setlinfoBean.setDscg_dept_code(cyksdm);
            setlinfoBean.setDscg_dept_name(baglBasy.getCyksmc());
            setlinfoBean.setTraf_dept_flat("0");
            if (baglBasy.getZkkbdm() != null && baglBasy.getZkkbdm().length() > 0) {
                setlinfoBean.setTraf_dept_flat("1");
            }
            setlinfoBean.setFixmedins_code(minsur410100.getFixmedins_code());
            setlinfoBean.setFixmedins_name(minsur410100.getFixmedins_name());
            setlinfoBean.setHi_no(minsur1101Baseinfo.getPsnNo());
            setlinfoBean.setMedcasno(inpNoByPid.getInpNo());
            setlinfoBean.setDcla_time(updateDate);
            setlinfoBean.setPsn_name(minsur1101Baseinfo.getPsnName());
            setlinfoBean.setGend(minsur1101Baseinfo.getGend());
            setlinfoBean.setBrdy(brty);
            setlinfoBean.setAge(baglBasy.getNl().toString());
            setlinfoBean.setNtly(baglBasy.getGj());
            String nationCode;
            if (StringUtils.isBlank(minsur1101Baseinfo.getNaty())) {
                nationCode = minsur2301ResultMapper.getNationCode(patientId);
                if (StringUtils.isBlank(nationCode)) {
                    nationCode = "01";
                }
            } else {
                nationCode = minsur1101Baseinfo.getNaty();
            }
            String ventUsedDura = minsur2301ResultMapper.getVentUsedDura(patientId, visitId);
            setlinfoBean.setVent_used_dura(ventUsedDura);
            setlinfoBean.setNaty(nationCode);
            setlinfoBean.setPatn_cert_type(minsur1101Baseinfo.getPsnCertType());
            setlinfoBean.setCertno(minsur1101Baseinfo.getCertno());
            setlinfoBean.setPrfs(baglBasy.getZy());
            setlinfoBean.setAct_ipt_days(Integer.valueOf(baglBasy.getZyts()));
            setlinfoBean.setCurr_addr(baglBasy.getXzz());
            setlinfoBean.setEmp_name(baglBasy.getGzdw() == null || StringUtils.isBlank(baglBasy.getGzdw()) || baglBasy.getGzdw().equals("无") || baglBasy.getGzdw().equals("_") ? "-" : baglBasy.getGzdw());
            setlinfoBean.setEmp_addr("-");
            setlinfoBean.setEmp_tel(baglBasy.getDwdh() == null || StringUtils.isBlank(baglBasy.getDwdh()) ? "-" : baglBasy.getDwdh());
            setlinfoBean.setPoscode(baglBasy.getYb());
            setlinfoBean.setConer_addr(baglBasy.getLxrdz());
            setlinfoBean.setConer_name(baglBasy.getLxrxm());
            setlinfoBean.setDays_rinp_flag_31(baglBasy.getZry31t());
            setlinfoBean.setDays_rinp_pup_31(baglBasy.getZry31tmd());
            setlinfoBean.setAcp_medins_name(baglBasy.getYzzyYljg());
            setlinfoBean.setConer_tel(baglBasy.getLxrdh());
            setlinfoBean.setPatn_rlts(baglBasy.getLxrgx().trim());
            setlinfoBean.setHi_type(minsur1101Insuinfo.getInsutype());
            setlinfoBean.setInsuplc(minsur1101Insuinfo.getInsuplcAdmdvs());
            List<TreatDays> teatAllDays = minsur2301ResultMapper.getTeatAllDays(patientId, visitId);
            TreatDays treatDays = teatAllDays.stream().filter(t -> t.getItemCode().equals("120100002")).findFirst().orElse(null);
            setlinfoBean.setSpga_nurscare_days(treatDays == null ? 0 : treatDays.getAmount());
            TreatDays treatDays1 = teatAllDays.stream().filter(t -> t.getItemCode().equals("120100003")).findFirst().orElse(null);
            setlinfoBean.setLv1_nurscare_days(treatDays1 == null ? 0 : treatDays1.getAmount());
            TreatDays treatDays2 = teatAllDays.stream().filter(t -> t.getItemCode().equals("120100004")).findFirst().orElse(null);
            setlinfoBean.setScd_nurscare_days(treatDays2 == null ? 0 : treatDays2.getAmount());
            TreatDays treatDays3 = teatAllDays.stream().filter(t -> t.getItemCode().equals("120100005")).findFirst().orElse(null);
            setlinfoBean.setLv3_nurscare_days(treatDays3 == null ? 0 : treatDays3.getAmount());
            //特殊人员类型异常
            String psnIdetType = minsur1101Idetinfo == null ? "9" : minsur1101Idetinfo.getPsnIdetType();
//                setlinfoBean.setSp_psn_type(StringUtils.isBlank(psnIdetType) ? "9" : psnIdetType);
            setlinfoBean.setSp_psn_type("9");
//                新生儿入院类型
            setlinfoBean.setNwb_adm_type("");
            //新生儿天数
            if (ObjectUtil.isNotNull(baglBasy.getNl()) && Double.parseDouble(baglBasy.getNl()) < 1) {
                Date csrq = baglBasy.getCsrq();
                Date date = baglBasy.getCyrq();
                long time = date.getTime() - csrq.getTime();
                int days = (int) Math.floor(time / 24 / 60 / 60 / 1000);
                if (days > 365) {
                    setlinfoBean.setAge(String.valueOf(DateUtil.getage(DateUtil.formatDate(csrq, "yyyy-MM-dd"), DateUtil.formatDate(date, "yyyy-MM-dd"))));
                } else {
                    setlinfoBean.setNwb_age(String.valueOf(days));
                    setlinfoBean.setAge("0");
                }
            }
            setlinfoBean.setNwb_bir_wt(baglBasy.getXsecstz());
            Map<String, String> admTimeAndDscgTime = minsur2301ResultMapper.getAdmTimeAndDscgTime(patientId, visitId);
//                setlinfoBean.setAdm_time(DateUtil.formatDate(baglBasy.getRysj(), "yyyy-MM-dd HH:mm:ss"));
            setlinfoBean.setAdm_time(admTimeAndDscgTime.get("ADMTIME"));
            setlinfoBean.setDcla_time(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
//                setlinfoBean.setDscg_time(DateUtil.formatDate(baglBasy.getCyrq(), "yyyy-MM-dd HH:mm:ss"));
            setlinfoBean.setDscg_time(admTimeAndDscgTime.get("DSCGTIME"));
            setlinfoBean.setOtp_wm_dise(baglBasy.getMjzzdmc());
            setlinfoBean.setWm_dise_code(baglBasy.getMjzzdbm());
            setlinfoBean.setDays_rinp_flag_31(baglBasy.getZry31t());
            setlinfoBean.setNwb_adm_wt(baglBasy.getXserytz());
            setlinfoBean.setIpt_med_type("1");
            setlinfoBean.setAdm_way(baglBasy.getRytj());
            setlinfoBean.setConer_tel(baglBasy.getLxrdh() == null || baglBasy.getLxrdh().equals("") ? "-" : baglBasy.getLxrdh());
            StaffDict respInsur = minsur1101BaseinfoMapper.getInsurCode(baglBasy.getZrhs());
            //判断给银海传主诊用病案回传的 zzys还是zyys
            String doctor = minsur2301ResultMapper.getDoctor();
            String zzys = baglBasy.getZzys();
            if (StringUtils.isNotBlank(doctor) && doctor.equals("1")) {
                zzys = baglBasy.getZyys();
            }
            StaffDict chfpdrInsur = minsur1101BaseinfoMapper.getInsurCode(zzys);
            if (ObjectUtil.isNotNull(respInsur)) {
                setlinfoBean.setResp_nurs_code(respInsur.getNationalNo());
                setlinfoBean.setResp_nurs_name(respInsur.getName());
//                    throw  new NullPointerException("setlId【" + setlId +"】病案首页’zrhs‘得不到操作人医保信息，核查后再上传！");
            }

            if (ObjectUtil.isNotNull(chfpdrInsur)) {
                setlinfoBean.setChfpdr_code(chfpdrInsur.getNationalNo());
                setlinfoBean.setChfpdr_name(chfpdrInsur.getName());
//                    throw  new NullPointerException("setlId【" + setlId +"】病案首页’zzys‘得不到操作人医保信息，核查后再上传！");
            }
            setlinfoBean.setDscg_way(baglBasy.getLyfs());
            //治疗类别
            setlinfoBean.setTrt_type("10");
            String rykb = baglBasy.getRykbdm();
            String apiDeptAdm = minsur2301ResultMapper.getApiDept(rykb);
            if (StringUtils.isNotBlank(apiDeptAdm)) {
                setlinfoBean.setAdm_caty(apiDeptAdm);
            }
            String Refldept_dept = "";
            if (StringUtils.isNotBlank(baglBasy.getZkkbdm())) {
                Refldept_dept = minsur2301ResultMapper.getApiDept(baglBasy.getZkkbdm());
                if (StringUtils.isNotBlank(baglBasy.getZkkbdm1())) {
                    Refldept_dept = Refldept_dept + "→" + minsur2301ResultMapper.getApiDept(baglBasy.getZkkbdm1());
                    if (StringUtils.isNotBlank(baglBasy.getZkkbdm2())) {
                        Refldept_dept = Refldept_dept + "→" + minsur2301ResultMapper.getApiDept(baglBasy.getZkkbdm2());
                        if (StringUtils.isNotBlank(baglBasy.getZkkbdm3())) {
                            Refldept_dept = Refldept_dept + "→" + minsur2301ResultMapper.getApiDept(baglBasy.getZkkbdm3());
                        }
                    }
                }
            }
            setlinfoBean.setRefldept_dept(Refldept_dept);
            String apiDeptDscg = minsur2301ResultMapper.getApiDept(cyksdm);
            setlinfoBean.setDscg_caty(apiDeptDscg);
            //主诊断标志
            setlinfoBean.setMaindiag_flag("1");
            setlinfoBean.setBld_cat("");
            //票据代码
            try {
                String materialBathno = minsur2301ResultMapper.getMaterialBathno(inpSettleMaster.getMaterialNo());
                setlinfoBean.setBill_code(StringUtils.isBlank(materialBathno) ? "-" : materialBathno);
            } catch (Exception e) {
                setlinfoBean.setBill_code("-");
//                    throw new NullPointerException("患者：【" + patientId+ "】第【" + visitId + "】次住院还未结算，同步结算清单【410100】异常！");
            }
            setlinfoBean.setBill_no(StringUtils.isBlank(inpSettleMaster.getMaterialNo()) ? "-" : inpSettleMaster.getMaterialNo());
            setlinfoBean.setBiz_sn(inpSettleMaster.getRcptNo());
            String setlDate = DateUtil.formatDate(minsur2304Setlinfo.getSetlTime(), "yyyy-MM-dd");
            setlinfoBean.setSetl_begn_date(setlDate);
            setlinfoBean.setSetl_end_date(setlDate);
            //个人自付
            setlinfoBean.setPsn_selfpay(new BigDecimal("0"));

            //个人账户支出
            setlinfoBean.setAcct_pay(minsur2304Setlinfo.getAcctPay());

            BigDecimal s = minsur2304Setlinfo.getPsnPartAmt();

            if (s != null && ObjectUtil.isNotNull(s)) {
                //个人自费
                setlinfoBean.setPsn_ownpay(s);
            } else {
                setlinfoBean.setPsn_ownpay(new BigDecimal("0"));
            }
            //个人现金支付
            setlinfoBean.setPsn_cashpay(minsur2304Setlinfo.getPsnCashPay() == null || ObjectUtil.isNull(s) ? new BigDecimal("0") : minsur2304Setlinfo.getPsnCashPay());
            //医保支付方式
            setlinfoBean.setHi_paymtd("9");
            setlinfoBean.setHsorg("610399");
            setlinfoBean.setHsorg_opter("-");
            if (jsonObject.getString("fixmedins_code").equals("H61030200230")) {
                setlinfoBean.setHi_setl_lv("3");
            } else {
                setlinfoBean.setHi_setl_lv("2");
            }
            setlinfoBean.setMedins_fill_dept(cyksdm);
            setlinfoBean.setMedins_fill_psn(jsonObject.getString("opter_name"));


            Map<String, String> map = JSON.parseObject(JSON.toJSONString(baglBasy), new TypeReference<Map<String, String>>() {
            });
            Set<String> strings = map.keySet();
            List<String> diseKeyList = new ArrayList<>();
            List<String> oprninfoKeyList = new ArrayList<>();

            for (String str : strings) {
                if (str.contains("zyssczbm")) {
                    oprninfoKeyList.add(str);
                }
                if (str.contains("qtzdbm")) {
                    diseKeyList.add(str);
                }
            }

            //diseinfo
            List<Minsur410100.InputBeanInsur.DiseinfoBean> diseinfoBeanList = new ArrayList<>();
            Minsur410100.InputBeanInsur.DiseinfoBean diseinfoBean = new Minsur410100.InputBeanInsur.DiseinfoBean();
            diseinfoBean.setMaindiag_flag("1");
            diseinfoBean.setDiag_type("1");
            int diseId=1;
            diseinfoBean.setid(String.valueOf(diseId));
            diseId++;
            diseinfoBean.setAdm_cond_type(baglBasy.getZyzdrybq());
            diseinfoBean.setDiag_code(baglBasy.getZyzdbm());
            diseinfoBean.setDiag_name(baglBasy.getZyzdmc());
            diseinfoBeanList.add(diseinfoBean);
            for (String disStr : diseKeyList) {
                String QTZDRYBQ = "qtzdrybq";
                String QTZDMC = "qtzdmc";
                if (!disStr.equals("qtzdrybq")) {
                    String qtzdbm = disStr.replace("qtzdbm", "");
                    QTZDRYBQ = QTZDRYBQ + qtzdbm;
                    QTZDMC = QTZDMC + qtzdbm;
                }
                if (StringUtils.isNotBlank(map.get(disStr))) {
                    Minsur410100.InputBeanInsur.DiseinfoBean diseinfoBeanOther = new Minsur410100.InputBeanInsur.DiseinfoBean();
                    diseinfoBeanOther.setMaindiag_flag("0");
                    diseinfoBeanOther.setDiag_type("1");
                    diseinfoBeanOther.setid(String.valueOf(diseId++));
                    diseinfoBeanOther.setAdm_cond_type(map.get(QTZDRYBQ));
                    diseinfoBeanOther.setDiag_code(map.get(disStr));
                    diseinfoBeanOther.setDiag_name(map.get(QTZDMC));
                    diseinfoBeanList.add(diseinfoBeanOther);
                }
            }
            inputBeanInsur.setDiseinfo(diseinfoBeanList);

            //iteminfo
            List<IteminfoBean> iteminfoBeanList = new ArrayList<>();
            minsur2301ResultList.stream().forEach(iteminfoBeanHIs -> {
                IteminfoBean item = new IteminfoBean();
                item.setAmt(iteminfoBeanHIs.getAmt());
                item.setClaa_sumfee(iteminfoBeanHIs.getClaaSumfee());
                item.setClab_amt(iteminfoBeanHIs.getClabAmt());
                item.setFulamt_ownpay_amt(iteminfoBeanHIs.getFulamtOwnpayAmt());
                item.setMed_chrgitm(iteminfoBeanHIs.getMedChrgitm());
                item.setOth_amt(iteminfoBeanHIs.getOthAmt());
                iteminfoBeanList.add(item);
            });
            inputBeanInsur.setIteminfo(iteminfoBeanList);
            //icuinfo
            List<IcuInfo> collect = minsur2301ResultMapper.getByorder(patientId, visitId, "%重症监护%");
            if (CollectionUtils.isNotEmpty(collect)) {
                List<Minsur410100.InputBeanInsur.IcuinfoBean> icuinfoBeanList = new ArrayList<>();
                String wordType = "";
                long nd = 1000 * 24 * 60 * 60; //每天毫秒数
                long nh = 1000 * 60 * 60; //每小时毫秒数
                long nm = 1000 * 60; //每分钟毫秒数
                for (IcuInfo adtLog : collect) {
                    Date startTime = adtLog.getStartDateTime();
                    if (adtLog.getOrderingDept().equals("030411")) {
                        wordType = "1";
                    } else {
                        wordType = "7";
                    }
                    Date endTime = adtLog.getStopDateTime();
                    Minsur410100.InputBeanInsur.IcuinfoBean icuinfoBean = new Minsur410100.InputBeanInsur.IcuinfoBean();
                    icuinfoBean.setScs_cutd_ward_type(wordType);
                    icuinfoBean.setScs_cutd_inpool_time(DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss"));
                    icuinfoBean.setScs_cutd_exit_time(DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss"));
                    //入重时长
                    long diff = endTime.getTime() - startTime.getTime();//获取两个时间差毫秒数
                    int day = (int) Math.floor(diff / nd);// 相差的天数
                    int hour = (int) Math.floor(diff % nd / nh); //相差的小时
                    int minutes = (int) Math.floor(diff % nd % nh / nm); //相差的分钟
                    icuinfoBean.setScs_cutd_sum_dura(day + "/" + hour + "/" + minutes);
                    icuinfoBeanList.add(icuinfoBean);
                }
                inputBeanInsur.setIcuinfo(icuinfoBeanList);
            }
            //payinfo
            List<Minsur410100.InputBeanInsur.PayinfoBean> payinfoBeanList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(minsur2304SetldetailList)) {
                for (Minsur2304Setldetail minsur2304Setldetail : minsur2304SetldetailList) {
                    Minsur410100.InputBeanInsur.PayinfoBean payinfoBean = new Minsur410100.InputBeanInsur.PayinfoBean();
                    payinfoBean.setFund_pay_type(minsur2304Setldetail.getFundPayType());
                    payinfoBean.setFund_payamt(minsur2304Setldetail.getFundPayamt());
                    payinfoBeanList.add(payinfoBean);
                }
            }
            inputBeanInsur.setPayinfo(payinfoBeanList);

            //oprninfo
            List<Minsur410100.InputBeanInsur.OprninfoBean> oprninfoBeanList = new ArrayList<>();
            int operId=1;
            for (String operStr : oprninfoKeyList) {
                String ZYSSCZBM = "zyssczbm";
                String ZYSSCZMC = "zyssczmc";
                String oprtType = "1";
                String ZYSSCZRQ = "zyssczrq";
                String ZYSSCZSZ = "zyssczsz";
                String ZYSSCZYS = "zyssczys";
                String ZYSSCZMZ = "zyssczmz";
                String mainOprnFlag = "1";
                if (!operStr.equals("zyssczbm")) {
                    String no = operStr.replace("zyssczbm", "");
                    ZYSSCZBM = ZYSSCZBM + no;
                    ZYSSCZMC = ZYSSCZMC + no;
                    ZYSSCZRQ = ZYSSCZRQ + no;
                    ZYSSCZSZ = ZYSSCZSZ + no;
                    ZYSSCZYS = ZYSSCZYS + no;
                    ZYSSCZMZ = ZYSSCZMZ + no;
                    mainOprnFlag = "0";
                    oprtType = "2";
                }
                if (StringUtils.isNotBlank(map.get(ZYSSCZBM))) {
                    Minsur410100.InputBeanInsur.OprninfoBean oprninfoBean = new Minsur410100.InputBeanInsur.OprninfoBean();
                    StaffDict insurCode = minsur1101BaseinfoMapper.getInsurCode(map.get(ZYSSCZSZ));
                    StaffDict anstCode = minsur1101BaseinfoMapper.getInsurCode(map.get(ZYSSCZYS));
                    oprninfoBean.setOprn_oprt_type(oprtType);
                    oprninfoBean.setOprn_oprt_code(map.get(ZYSSCZBM));
                    oprninfoBean.setOprn_oprt_name(map.get(ZYSSCZMC));
                    oprninfoBean.setMain_oprn_flag(mainOprnFlag);
                    String operDateStr = map.get(ZYSSCZRQ);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String time = simpleDateFormat.format(new Date(Long.parseLong(operDateStr)));
                    Date parse = simpleDateFormat.parse(time);
                    String s1 = DateUtil.formatDate(parse, "yyyy-MM-dd");
                    oprninfoBean.setOprn_oprt_date(s1);
                    oprninfoBean.setOprn_oprt_begntime(s1);
                    oprninfoBean.setOprn_oprt_endtime(s1);
                    oprninfoBean.setAnst_begntime(s1);
                    oprninfoBean.setAnst_endtime(s1);
                    if (insurCode != null) {
                        oprninfoBean.setOper_dr_code(insurCode.getNationalNo());
                        oprninfoBean.setOper_dr_name(insurCode.getName());
                    }
                    if (anstCode != null) {
                        oprninfoBean.setAnst_dr_code(anstCode.getNationalNo());
                        oprninfoBean.setAnst_dr_name(anstCode.getName());
                    }
                    oprninfoBean.setAnst_way(map.get(ZYSSCZMZ));
                    oprninfoBean.setid(String.valueOf(operId));
                    operId ++;
                    oprninfoBeanList.add(oprninfoBean);
                }
            }
            inputBeanInsur.setOprninfo(oprninfoBeanList);
            minsur410100.setInput(inputBeanInsur);
            setlinfoBean.setDiag_code_cnt(diseinfoBeanList.size());
            if (ObjectUtil.isNotNull(oprninfoBeanList.size()) && oprninfoBeanList.size() > 0) {
                setlinfoBean.setOprn_oprt_code_cnt(oprninfoBeanList.size());
            }
            inputBeanInsur.setSetlinfo(setlinfoBean);
            String endesUrl = insuranceLogsMapper.getDipUrl();
//                String desBipUrl = insuranceLogsMapper.getDESBipUrl();
            wxPayFunc.sendRefundBillMsg(JSON.toJSONString(minsur410100), endesUrl, restTemplate, "银海dip");
//                wxPayFunc.sendRefundBillMsg(JSON.toJSONString(minsur410100), desBipUrl, restTemplate, "ESB平台");
        }
    }

    public void getInsurBase(String patientId, String idNo, String infno, JSONObject jsonObject, String visitId) {
        InputComm inputComm = new InputComm();
        inputComm.setInput(jsonObject);
        //准备基础信息
        HospitalConfig hospitalConfig = hospitalConfigMapper.getOne(new QueryWrapper<>());
        String no = insuranceLogsMapper.getNo();
        String sysdateStr = insuranceLogsMapper.getSysdateStr();
        String fixmedinsCode = hospitalConfig.getFixmedinsCode();
        String msgid = fixmedinsCode + sysdateStr + no;
        inputComm.setInf_time(DateUtil.getTime());
        inputComm.setMsgid(msgid);
        inputComm.setInfno(infno);
        inputComm.setVisit_id(visitId);
        inputComm.setOpter("0000");
        inputComm.setOpter_name("后台操作");
        inputComm.setOpter_type("1");
        inputComm.setMdtrtarea_admvs(hospitalConfig.getMdtrtareaAdmvs());
        inputComm.setFixmedins_code(fixmedinsCode);
        inputComm.setFixmedins_name(hospitalConfig.getHospital());
        inputComm.setPatient_id(patientId);
        inputComm.setInsuplc_admdvs(StringUtils.substring(idNo, 0, 6));
        String weChatUrl = insuranceLogsMapper.getWeChatUrl("INSURANCE_MOVE_URL");
//        String weChatUrl = "http://192.168.13.230:8085/insurimp/patinfo";
        Tip tip = pushMessage.pushAlipayMsg(JSON.toJSONString(inputComm), weChatUrl, restTemplate);
    }
}
